
/**
 * js通用工具类
 * create by @ronghui.xiao @2016-4-22
 */
var CommonUtil = {};

/**
 * 获取浏览器地址栏参数
 * create by ronghui.xiao @2015-7-3
 */
CommonUtil.getUrlParams = function(){
	   return this.getParamsByUrl(window.document.URL);
};

/**
 * 获取浏览器地址栏参数
 * create by ronghui.xiao @2015-7-3
 */
CommonUtil.getParamsByUrl = function(url){
	    var whIndex = url.indexOf("?") +1;
	    var jhIndex = url.indexOf("#"); 
		var str = jhIndex != -1 ? url.substring(whIndex , jhIndex) : url.substring(whIndex);
		var arr = str.split("&");
	 	var params = {};
		for(var i = 0 ; i< arr.length; i ++){
			var itemArr = arr[i].split("=");
		    params[itemArr[0]]=decodeURIComponent(itemArr[1]);
		}
	   return params;
};

CommonUtil.getLocationParams = function(name){
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var url = window.location.href;
    var r = url.substr(url.indexOf("?") + 1).match(reg);
    if(r!=null)return  unescape(r[2]); return null;
};

/**
 * 获取当前时间
 * 格式 : yyyy-MM-dd HH:mm:ss
 * create by ronghui.xiao @2015-11-19
 */
CommonUtil.getCurrentTimeYmdhms = function(){
    return  this.getDateYmdhms(new Date());
};

/**
 * 获取当前时间
 * 格式 : yyyy-MM-dd HH:mm:ss
 * create by ronghui.xiao @2015-11-19
 */
CommonUtil.getDateYmdhms = function(date){
    var _year = date.getFullYear();
    var _month = date.getMonth()+1;
    var _data = date.getDate();
    var _hour = date.getHours();
    var _min = date.getMinutes();
    var _sec = date.getSeconds();
    if(_month<10) _month = '0' + _month;
    if(_data<10)  _data  = '0' + _data;
    if(_hour<10)  _hour  = '0' + _hour;
    if(_min<10)   _min   = '0' + _min;
    if(_sec<10)   _sec   = '0' + _sec;
    return  _year+"-"+_month+"-"+_data +" "+_hour+":"+_min+":"+_sec;
};

/**
 * 创建一个以时间为格式的编号
 * 格式 : yyyy-MM-dd HH:mm:ss
 * create by ronghui.xiao @2015-11-19
 */
CommonUtil.createDateNo = function(){
	var date = new Date();
    var _year = date.getFullYear();
    var _month = date.getMonth()+1;
    var _data = date.getDate();
    var _hour = date.getHours();
    var _min = date.getMinutes();
    var _sec = date.getSeconds();
    if(_month<10) _month = '0' + _month;
    if(_data<10)  _data  = '0' + _data;
    if(_hour<10)  _hour  = '0' + _hour;
    if(_min<10)   _min   = '0' + _min;
    if(_sec<10)   _sec   = '0' + _sec;
    return  "" + _year+_month+_data +_hour+_min+_sec;
};

CommonUtil.formatUnixTime = function(unixTime) {
	if(unixTime) {
		var unixTimestamp = new Date(unixTime);
	    return CommonUtil.getDateYmdhms(unixTimestamp);
	} else {
		return "";
	}
}

/**
 * 获取当前日期
 * 格式 : yyyy-MM-dd
 * create by ronghui.xiao @2015-11-19
 */
CommonUtil.getCurrentTimeYmd=function(){
	    return this.getDateYmd(new Date());
}

/**
 * 获取日期的ydm格式
 * 格式 : yyyy-MM-dd
 * create by ronghui.xiao @2015-11-19
 */
CommonUtil.getDateYmd=function(date){
	 	var myDate = new Date(date);
	    var _year = myDate.getFullYear();
	    var _month = myDate.getMonth()+1;
	    var _data = myDate.getDate();
	    if(_month<10) _month = '0' + _month;
	    if(_data<10)  _data  = '0' + _data;
	    return  _year+"-"+_month+"-"+_data;
}

//获取日期的0点时刻字符串
CommonUtil.getDateZeroPointStr = function(date){
	return CommonUtil.getDateYmd(date) + " 00:00:00"
}

//获取日期的23:59:59时刻字符串
CommonUtil.getDateLastPointStr = function(date){
	return CommonUtil.getDateYmd(date) + " 23:59:59";
}

/**
 * 获取日期的0点时刻
 * 格式 : yyyy-MM-dd
 * create by ronghui.xiao @2015-11-19
 */
CommonUtil.getDateZeroPoint=function(dateStr){
	return dateStr + " 00:00:00";
}

//日期加上天数后的新日期.
CommonUtil.addDays = function(date,days){
	  var nd = new Date(date);
	  nd = nd.valueOf();
	  nd = nd + days * 24 * 60 * 60 * 1000;
	  nd = new Date(nd);
	  return nd;
}

/**
 * 获取日期的23:59:59点时刻
 * 格式 : yyyy-MM-dd
 * create by ronghui.xiao @2015-11-19
 */
CommonUtil.getDateLastPoint=function(dateStr){
	return dateStr + " 23:59:59"
}

/**
 * 传入对象或参数是否为空 true为空 false为存在
 * create by ronghui.xiao @2016-04-22
 */
CommonUtil.isNull = function(param){
    return param == null || param == undefined;
};

/**
 * 传入对象或参数是否为空 true为空 false为存在
 * create by ronghui.xiao @2016-04-22
 */
CommonUtil.isEmpty = function(param){
    return param == null  || param == undefined || param == "" || param.length == 0;
};

/**
 * 验证对象是否不为空
 * @param param
 * create by ronghui.xiao @2016-04-22
 */
CommonUtil.isNotNull = function(param){
    return !this.isNull(param);
};

/**
 * 使超出当前div宽度的图片与div宽度相等
 * param div_id 当前div的id
 * create by chong.luo @2015-12-28
 */
CommonUtil.imgHandle = function(div_id){
    var div_width = $("#"+div_id).width();
    $("#"+div_id).find("img").each(function(){
        $(this).hide();
        var obj = this;
        CommonUtil.imgLoadAfter(this, function(){//轮询
            $(obj).show();
            if(obj.width>div_width){obj.width=div_width;}
        });
    });
};
CommonUtil.imgLoadAfter=function(img, callback) {
    var timer = setInterval(function() {
        if (img.complete) {
            callback(img);
            clearInterval(timer);
        }
    }, 50);
};

/**
 *
 * 若参数是脚本,执行脚本里面的内容
 * create by ronghui.xiao @2016-01-24
 */
CommonUtil.executeScritByData = function(data){
    if(data && data.length > 0 && data.indexOf("<script>") != -1 && data.indexOf("</script>")!= -1){
        eval(data.substring(data.indexOf("<script>") + "<script>".length ,data.indexOf("</script>")));
    }
};

/**
 * 判断参数是否是一个对象
 * create by ronghui.xiao @2016-04-22
 */
CommonUtil.isObject = function(param){
    return this.isNotNull(param)  && typeof param == "object";
};

/**
 *
 * 判断对象是否是一个空对象
 * create by ronghui.xiao @2016-04-22
 */
CommonUtil.isObjectEmpty = function(obj){
    if(this.isObject(obj)){
        for(var key in obj){
            if(key != undefined){
                return false;
            }
        }
    }
    return true;
};

/**
 *
 * 判断对象是否不为空对象
 * create by ronghui.xiao @2016-04-22
 */
CommonUtil.isObjectNotEmpty = function(obj){
    return !this.isObjectEmpty(obj);
};

/**
*
* 获取一个字符串中指定字符串第n次出现的位置
*/
CommonUtil.findPosition = function (str,cha,num){
    var x=str.indexOf(cha);
    for(var i=0;i<num;i++){
        x=str.indexOf(cha,x+1);
    }
    return x;
};

/**
 *
 * 把目标对象的属性全部拷贝到源目标对象中
 * create by ronghui.xiao @2016-01-25
 */
CommonUtil.copyProperties = function( sourceObj , targetObj){
    if(this.isObjectNotEmpty(sourceObj) && this.isObjectNotEmpty(targetObj)){
        for(var key in targetObj){
            sourceObj[key] = targetObj[key];
        }
    }
    return sourceObj;
};

/**
*
* 生成UUID
* create by ronghui.xiao @2016-01-25
*/
CommonUtil.generateUUID = function(){
	var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    s[8] = s[13] = s[18] = s[23] = "-";
    var uuid = s.join("");
    return uuid;
};

/**
*
* 生成唯一变量名
* create by ronghui.xiao @2018-06-14
*/
CommonUtil.generateVariableName = function(){
	return "var_" + CommonUtil.generateUUID().replace(/-/g,"_");
}

/**
 * 创建重复执行方法的定时任务
 * taskTimerName : 任务名称
 * millisecond : 毫秒数
 * fun : 方法名
 * create by ronghui.xiao @2016-09-18
 */
CommonUtil.setInterval = function(taskTimerName,millisecond,fun){
	window[taskTimerName] = setInterval(fun,millisecond);
};

/**
 * 清除定时任务
 * taskTimerName : 定时任务名称
 * create by ronghui.xiao @2016-09-18
 */
CommonUtil.clearInterval = function(taskTimerName){
	clearInterval(window[taskTimerName]);
	delete window[taskTimerName];
};

/**
 * 处理手机号码（敏感信息过滤）
 * mobileNumber : 手机号码
 */
CommonUtil.mobileNumberFilter = function(mobileNumber){
	var mobileNumberDisplay = "";
	if(!this.isNull(mobileNumber)) {
		mobileNumberDisplay = mobileNumber.substring(0,3)+"****"+mobileNumber.substring(8,11)
	}
	return mobileNumberDisplay;
};

/**
 * 如果param为undefind或为null等,填充空白
 */
CommonUtil.fillBlank = function(param){
	return this.isNull(param) ? "" : param + "";
}

/*把对象转化成&连接的字符串*/
CommonUtil.formatParamsStr = function(obj){
    var paramsTxt = "";
    if(obj  && typeof obj == "object"){
        for(var key in obj){
            paramsTxt += "&" + key + "=" + obj[key];
        }
        if(paramsTxt.length > 0) paramsTxt = paramsTxt.substring(1);
    }
    return paramsTxt;
};

/*把对象转化成&连接的字符串,不包含值为空字符串的key*/
CommonUtil.formatParamsStrExceptBlank= function(obj){
    var paramsTxt = "";
    if(obj  && typeof obj == "object"){
        for(var key in obj){
        	var value = $.trim(obj[key]);
        	if(value != ""){
        		paramsTxt += "&" + key + "=" + obj[key];
        	}
        }
        if(paramsTxt.length > 0) paramsTxt = paramsTxt.substring(1);
    }
    return paramsTxt;
};

//获取obj中的所有key,返回一个数组
CommonUtil.keysArray = function(obj){
	 if(obj  && typeof obj == "object"){
		 var arr = [];
		 for(var key in obj){
			 arr.push(key);
		 }
		 return arr;
	 }
}

//查询元素在数组中的位置
CommonUtil.findArrayIndexByElement = function(arr,element){
	  for(var i = 0; i < arr.length ; i ++){
		  if(arr[i] == element){
			  return i;
		  }
	  }
}
//对象合并
CommonUtil.extend=function(o,n){
   for (var p in n){
        if(n.hasOwnProperty(p) && (!o.hasOwnProperty(p) ))
            o[p]=n[p];
    }
};

CommonUtil.ccTreeWalk = (function () {

  var toString = Object.prototype.toString;

  var $ = {
    type: function (obj) {
      if (obj === null) return 'null';
      else if (obj === undefined) return 'undefined';
      else if (typeof obj !== 'object') return typeof obj;
      else {
        var str = toString.call(obj);
        return str.slice(8, -1).toLowerCase();
      }
    },
    isWindow: function (node) {
      return node && node.window === node;
    }
  };

  function isArraylike( obj ) {
    var length = "length" in obj && obj.length,
      type = $.type( obj );

    if ( type === "function" || $.isWindow( obj ) ) {
      return false;
    }

    if ( obj.nodeType === 1 && length ) {
      return true;
    }

    return type === "array" || length === 0 ||
      typeof length === "number" && length > 0 && ( length - 1 ) in obj;
  }

  function treeWalk(item, callback, prop, y, x, parent) {
    if (item == null) return;
    if (y == null) y = 0;
    if (x == null) x = 0;
    if (callback(item, y, x, parent) === false) return false;

    if (prop == null) prop = 'children';
    if (!item[prop] || !isArraylike(item[prop])) return;

    var i = -1, len = item[prop].length, one;
    while (++i < len) {
      one = item[prop][i];

      if (one == null) continue;

      if (one[prop]) {
        if (treeWalk(one, callback, prop, y + 1, i, item) === false) {
          return false;
        }
      } else if (callback(one, y + 1, i, item) === false) {
        return false;
      }
    }
  };

  return treeWalk;
})();


//获取url参数
CommonUtil.GetQueryString=function(name){ 
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
  var r = window.location.search.substr(1).match(reg); 
  if (r != null) return decodeURIComponent(r[2]); 
  return null; 
};

//显示提示信息
CommonUtil.showMsg = function(type , msg){
	new $.zui.Messager('提示消息：'+msg, {icon:'times',type: type ,placement: 'center',time:'2000'}).show();
}

//显示错误信息
CommonUtil.showErrorMsg = function(msg){
	this.showMsg("danger" , msg);
}

//显示成功信息
CommonUtil.showSuccessMsg = function(msg){
	this.showMsg("success" , msg);
}


//显示成功信息
CommonUtil.isJson = function(content){
	
	try{
		
		JSON.parse(content);
		
		return true;
	}catch(e){
		console.log(e);
		return false;
	}
	
}


/*加载js*/
CommonUtil.loadScript = function(url , callback) {

 //若已经存在就不要加载了
  if($('body').find('script[src="'+url+'"]').length > 0)
	  return;
  
    var script = document.createElement("script");
    script.type = "text/javascript";
    
    if (typeof(callback) != "undefined") {
        if (script.readyState) {
            script.onreadystatechange = function() {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else {
            script.onload = function() {
                callback();
            };
        }
    };
    
    script.src = url;
    
	document.body.appendChild(script);
}

//回车触发某事件
CommonUtil.bindEnterKeyEvent = function(fn){
	this.bindEventByKeyCode(13 , fn);
}

//任意键绑定事件
CommonUtil.bindEventByKeyCode = function(keyCode , fn){
	
	$(document).unbind("keyup").keyup(function(event){
		
		event = event ? event : window.event;
		
		if(event.keyCode == keyCode){
			fn();
		}
		
	});
	
}

CommonUtil.guid = function() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
    return v.toString(16);
  });
};


/**
 * 获取某个父标签ID下面的所有表单参数
 * 
 * parentId : 父标签的ID
 * formNameArray : 表单名字数组
 * isRemoveEmptyParameter : 是否移除空的参数
 */
CommonUtil.getFormParams = function(parentId , formNameArray , isRemoveEmptyParameter){

	var jqParent = $("#" + parentId);
	
	var params = {};
	
	for(var i = 0 ; i < formNameArray.length ; i ++){
		
		var item = formNameArray[i];
		var formValue = $.trim(jqParent.find('[name="'+item+'"]').val())
		
		if(isRemoveEmptyParameter && formValue == "" ) continue;
		
		params[item] = formValue;
	}
	
	return params;
	
}

/**
 * propName : 属性名称
 * 返回 : 排序逻辑function
 */
CommonUtil.sortRank = function(propName){
	return function (obj1, obj2) {
	        var val1 = obj1[propName];
	        var val2 = obj2[propName];
	        if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
	            val1 = Number(val1);
	            val2 = Number(val2);
	        }
	        if (val1 < val2) { //降序排列
	            return 1;
	        } else if (val1 > val2) {
	            return -1;
	        } else {
	            return 0;
	        }
        };    
}

/**
 * 根据数组里面的属性名称排序
 */
CommonUtil.sortArrayByPropName = function(arr , propName){
	return arr.sort(this.sortRank(propName));
}


